using System;
using System.Linq;
using AAA.Db;
using AAA.Models;
using Microsoft.EntityFrameworkCore;

namespace AAA.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly DemoDb _db;
        private readonly DbSet<T> _table;
        public IQueryable<T> Table
        {
            get{return _table as IQueryable<T>;}
        }
        public EfRepository()   //调用就可以进行增删更新
        {
            _db=new DemoDb();
            _table=_db.Set<T>();
        }
        public void Delect(int id)    //删除
        {
            var entity=_table.Where(x=>x.ID==id).FirstOrDefault();
            if(entity==null){
                throw new System.Exception();
            }
            _table.Remove(entity);
            _db.SaveChanges();
        }

        public void Insert(T entity)
        {
            entity.IsActiced=true;
            entity.IsDelected=false;
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.DisplayOrder=0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            if(entity==null){
                throw new System.Exception();
            }
            if(entity.ID==0){
                throw new System.Exception();
            }
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }

        public void Delect(T entity)
        {
            throw new System.NotImplementedException();
        }
    }
}